package com.atguigu.servlet;

import javax.servlet.*;
import java.io.File;
import java.io.IOException;

/**
 * Date:2021/3/9
 * Author:ybc
 * Description:
 */
public class FirstServlet implements Servlet {

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        //ServletConfig的功能1：获取servlet的友好名称
        String servletName = servletConfig.getServletName();
        System.out.println("servlet的友好名称-->"+servletName);
        //ServletConfig的功能2：获取servlet的初始化参数
        String testInitParam = servletConfig.getInitParameter("testInitParam");
        System.out.println("servlet的初始化参数-->"+testInitParam);
        //ServletConfig的功能3：获取ServletContext对象
        ServletContext servletContext = servletConfig.getServletContext();
        //ServletContext的功能1：获取当前工程的初始化参数
        String testContextParam = servletContext.getInitParameter("testContextParam");
        System.out.println("当前工程的初始化参数-->"+testContextParam);
        //ServletContext的功能2：获取上下文路径
        String contextPath = servletContext.getContextPath();
        System.out.println("上下文路径-->"+contextPath);
        /**
         * ServletContext的功能3：获取当前工程的部署路径（输出路径或编译路径）
         * servletContext.getRealPath("")：获取当前工程的部署路径
         * D:\IDEA\workspace\SH0108\out\artifacts\day06_servlet_war_exploded
         * servletContext.getRealPath("test");获取当前工程的部署路径下某个目录的路径
         * D:\IDEA\workspace\SH0108\out\artifacts\day06_servlet_war_exploded\photo
         */
        String realPath = servletContext.getRealPath("photo");
        //获取realPath所对应的File文件对象
        File file = new File(realPath);
        //判断File所对应的目录是否存在
        if(!file.exists()){
            //若不存在，则创建目录
            file.mkdir();
        }
        System.out.println("当前工程的部署路径-->"+realPath);
        //ServletContext的功能4：作为一个域对象，可以在整个工程的范围中共享数据
        String testServletContext = (String) servletContext.getAttribute("testServletContext");
        System.out.println("获取ServletContext共享的数据-->"+testServletContext);
    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        servletRequest.getRequestDispatcher("/success.html").forward(servletRequest, servletResponse);
    }

    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void destroy() {

    }
}
